<template>
  <div class="product-detail-container">
    <div class="product-detail-content">
      <!-- 商品基本信息 -->
      <div class="product-info-section">
        <div class="product-images">
          <div class="main-image">
            <el-image
              :src="currentImage"
              fit="cover"
              class="main-img"
              :preview-src-list="product.images || [product.image]"
            />
          </div>
          <div class="image-thumbnails" v-if="product.images && product.images.length > 1">
            <div 
              v-for="(img, index) in product.images"
              :key="index"
              class="thumbnail"
              :class="{ active: currentImage === img }"
              @click="currentImage = img"
            >
              <el-image :src="img" fit="cover" />
            </div>
          </div>
        </div>
        
        <div class="product-details">
          <h1 class="product-title">{{ product.name }}</h1>
          <div class="product-subtitle">{{ product.subtitle }}</div>
          
          <div class="product-price">
            <span class="current-price">¥{{ product.price }}</span>
            <span v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">
              ¥{{ product.originalPrice }}
            </span>
            <el-tag v-if="product.discount" type="danger" size="small">
              {{ Math.round((1 - product.price / product.originalPrice) * 100) }}% OFF
            </el-tag>
          </div>
          
          <div class="product-meta">
            <div class="meta-item">
              <span class="label">销量：</span>
              <span class="value">{{ product.salesCount || 0 }}</span>
            </div>
            <div class="meta-item">
              <span class="label">库存：</span>
              <span class="value" :class="{ 'low-stock': product.stock < 10 }">
                {{ product.stock || 0 }}
              </span>
            </div>
            <div class="meta-item">
              <span class="label">分类：</span>
              <span class="value">{{ product.categoryName }}</span>
            </div>
          </div>
          
          <div class="product-rating" v-if="product.rating">
            <el-rate
              v-model="product.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}分"
            />
            <span class="rating-count">({{ product.reviewCount }}人评价)</span>
          </div>
          
          <div class="quantity-selector">
            <span class="label">数量：</span>
            <el-input-number
              v-model="quantity"
              :min="1"
              :max="product.stock"
              size="large"
            />
          </div>
          
          <div class="product-actions">
            <el-button 
              type="primary" 
              size="large" 
              :disabled="product.stock === 0"
              @click="addToCart"
              :loading="addingToCart"
            >
              <el-icon><ShoppingCart /></el-icon>
              {{ product.stock === 0 ? '缺货' : '加入购物车' }}
            </el-button>
            <el-button 
              type="danger" 
              size="large" 
              :disabled="product.stock === 0"
              @click="buyNow"
            >
              立即购买
            </el-button>
            <el-button 
              size="large" 
              :icon="product.isFavorite ? 'StarFilled' : 'Star'"
              :type="product.isFavorite ? 'danger' : 'default'"
              @click="toggleFavorite"
            >
              {{ product.isFavorite ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品详情标签页 -->
      <div class="product-tabs">
        <el-card>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="商品详情" name="description">
              <div class="description-content">
                <div v-if="product.description" v-html="product.description"></div>
                <div v-else class="no-content">暂无商品详情</div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="规格参数" name="specifications">
              <div class="specifications-content">
                <el-descriptions :column="2" border v-if="product.specifications">
                  <el-descriptions-item 
                    v-for="(value, key) in product.specifications"
                    :key="key"
                    :label="key"
                  >
                    {{ value }}
                  </el-descriptions-item>
                </el-descriptions>
                <div v-else class="no-content">暂无规格参数</div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane :label="`用户评价(${reviews.length})`" name="reviews">
              <div class="reviews-content">
                <div 
                  v-for="review in reviews"
                  :key="review.id"
                  class="review-item"
                >
                  <div class="review-user">
                    <el-avatar :src="review.userAvatar" :size="40" />
                    <div class="user-info">
                      <div class="username">{{ review.username }}</div>
                      <div class="review-time">{{ formatTime(review.createTime) }}</div>
                    </div>
                    <el-rate
                      v-model="review.rating"
                      disabled
                      size="small"
                    />
                  </div>
                  <div class="review-content">
                    {{ review.content }}
                  </div>
                  <div class="review-images" v-if="review.images && review.images.length">
                    <el-image
                      v-for="(img, index) in review.images"
                      :key="index"
                      :src="img"
                      fit="cover"
                      class="review-img"
                      :preview-src-list="review.images"
                    />
                  </div>
                </div>
                <div v-if="reviews.length === 0" class="no-content">
                  暂无用户评价
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <!-- 相关推荐 -->
      <div class="related-products">
        <el-card>
          <template #header>
            <span>相关推荐</span>
          </template>
          <div class="related-products-grid">
            <div 
              v-for="relatedProduct in relatedProducts"
              :key="relatedProduct.id"
              class="related-product-item"
              @click="goToProduct(relatedProduct.id)"
            >
              <el-image
                :src="relatedProduct.image || '/default-product.jpg'"
                fit="cover"
                class="related-image"
              />
              <div class="related-info">
                <h4>{{ relatedProduct.name }}</h4>
                <div class="related-price">¥{{ relatedProduct.price }}</div>
                <div class="related-sales">销量 {{ relatedProduct.salesCount }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getProductDetail, 
  getRelatedProducts,
  getProductReviews,
  addToCart as apiAddToCart,
  favoriteProduct,
  unfavoriteProduct
} from '@/api/mall'

const route = useRoute()
const router = useRouter()

// 响应式数据
const product = ref({})
const relatedProducts = ref([])
const reviews = ref([])
const quantity = ref(1)
const activeTab = ref('description')
const currentImage = ref('')
const addingToCart = ref(false)

// 获取商品详情
const loadProductDetail = async () => {
  try {
    const response = await getProductDetail(route.params.id)
    if (response.code === 200) {
      product.value = response.data
      currentImage.value = product.value.image || product.value.images?.[0]
      loadRelatedProducts()
      loadReviews()
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 获取相关推荐
const loadRelatedProducts = async () => {
  try {
    const response = await getRelatedProducts(product.value.id)
    if (response.code === 200) {
      relatedProducts.value = response.data || []
    }
  } catch (error) {
    console.error('获取相关推荐失败:', error)
  }
}

// 获取用户评价
const loadReviews = async () => {
  try {
    const response = await getProductReviews(product.value.id)
    if (response.code === 200) {
      reviews.value = response.data || []
    }
  } catch (error) {
    console.error('获取用户评价失败:', error)
  }
}

// 加入购物车
const addToCart = async () => {
  try {
    addingToCart.value = true
    await apiAddToCart({
      productId: product.value.id,
      quantity: quantity.value
    })
    ElMessage.success('已加入购物车')
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  } finally {
    addingToCart.value = false
  }
}

// 立即购买
const buyNow = () => {
  // 跳转到结算页面
  router.push({
    path: '/mall/checkout',
    query: {
      productId: product.value.id,
      quantity: quantity.value
    }
  })
}

// 切换收藏
const toggleFavorite = async () => {
  try {
    if (product.value.isFavorite) {
      await unfavoriteProduct(product.value.id)
      product.value.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      await favoriteProduct(product.value.id)
      product.value.isFavorite = true
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 跳转到其他商品
const goToProduct = (productId) => {
  router.push(`/mall/product/${productId}`)
}

// 工具函数
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 页面加载
onMounted(() => {
  loadProductDetail()
})
</script>

<style lang="scss" scoped>
.product-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.product-detail-content {
  max-width: 1200px;
  margin: 0 auto;
}

.product-info-section {
  display: flex;
  gap: 40px;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .product-images {
    flex-shrink: 0;
    
    .main-image {
      width: 400px;
      height: 400px;
      margin-bottom: 10px;
      
      .main-img {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }
    }
    
    .image-thumbnails {
      display: flex;
      gap: 8px;
      
      .thumbnail {
        width: 60px;
        height: 60px;
        border: 2px solid transparent;
        border-radius: 4px;
        cursor: pointer;
        
        &.active {
          border-color: #409eff;
        }
        
        .el-image {
          width: 100%;
          height: 100%;
          border-radius: 4px;
        }
      }
    }
  }
  
  .product-details {
    flex: 1;
    
    .product-title {
      font-size: 24px;
      font-weight: 600;
      margin: 0 0 10px 0;
      color: #303133;
    }
    
    .product-subtitle {
      color: #606266;
      font-size: 16px;
      margin-bottom: 20px;
    }
    
    .product-price {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 20px;
      
      .current-price {
        font-size: 28px;
        font-weight: bold;
        color: #e6a23c;
      }
      
      .original-price {
        font-size: 16px;
        color: #909399;
        text-decoration: line-through;
      }
    }
    
    .product-meta {
      margin-bottom: 20px;
      
      .meta-item {
        display: flex;
        margin: 8px 0;
        
        .label {
          color: #909399;
          width: 60px;
        }
        
        .value {
          color: #303133;
          
          &.low-stock {
            color: #f56c6c;
            font-weight: bold;
          }
        }
      }
    }
    
    .product-rating {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 20px;
      
      .rating-count {
        color: #909399;
        font-size: 14px;
      }
    }
    
    .quantity-selector {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 30px;
      
      .label {
        color: #303133;
        font-weight: 500;
      }
    }
    
    .product-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.product-tabs,
.related-products {
  margin-bottom: 20px;
  
  .description-content,
  .specifications-content,
  .reviews-content {
    min-height: 200px;
    
    .no-content {
      text-align: center;
      color: #909399;
      padding: 60px 0;
    }
  }
  
  .review-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .review-user {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 8px;
      
      .user-info {
        flex: 1;
        
        .username {
          font-weight: 500;
          color: #303133;
        }
        
        .review-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
    
    .review-content {
      color: #606266;
      line-height: 1.5;
      margin-bottom: 8px;
    }
    
    .review-images {
      display: flex;
      gap: 8px;
      
      .review-img {
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }
    }
  }
}

.related-products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  
  .related-product-item {
    cursor: pointer;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-2px);
    }
    
    .related-image {
      width: 100%;
      height: 150px;
      border-radius: 4px;
      margin-bottom: 8px;
    }
    
    .related-info {
      h4 {
        margin: 0 0 8px 0;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .related-price {
        color: #e6a23c;
        font-weight: bold;
        margin-bottom: 4px;
      }
      
      .related-sales {
        color: #909399;
        font-size: 12px;
      }
    }
  }
}

@media (max-width: 768px) {
  .product-detail-container {
    padding: 10px;
  }
  
  .product-info-section {
    flex-direction: column;
    padding: 20px;
    
    .product-images .main-image {
      width: 100%;
      height: 300px;
    }
    
    .product-actions {
      flex-direction: column;
    }
  }
  
  .related-products-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>
